<?php
class ajaxController extends base
{
    private $redisKeyBase; 
    public function __construct()
    {        
        parent::__construct('default');
        $this->redisKeyBase=REDIS_PREFIX.'gear_';
        //if(!common::is_ajax())exit ('非法访问');
    }
    /**
     * 喜欢装备
    */
    public function dolikeGear()
    {
        $code = 2;
        $msg = '失败';
        $rel = array('code' => & $code, 'msg' => & $msg);
        $gearId = common::request('gearId', 'G');
        $token = common::request('token', 'G');
        $islike = common::request('like', 'G');  // 是否已喜欢

        $tokenArr = explode('-', $token);
        $uid = intval($tokenArr[0]);
        $time = isset($tokenArr[1]) ? intval($tokenArr[1]):'';
        $md5Str = isset($tokenArr[2]) ? trim($tokenArr[2]):'';
        $tokenStr = $this->config['tokenStr'];
        if(md5($uid.$time.$tokenStr) != $md5Str)
        {
            $code = 1;
            $msg = '亲， 请先登录';
            exit(json_encode($rel));
        }
        
        $gearId = intval($gearId);
        if($islike)
        {
            if($this->load('gear')->unlikeGear($gearId, $uid))
            {
                $code = -1;
                $msg = '';
            }
        }
        else
        {
            if($this->load('gear')->likeGear($gearId, $uid))
            {
                $code = 1;
                $msg = '';
            }
        }
        exit(json_encode($rel));
    }    
       
    /**
    *+2.5.0
    *@from /c=admin&a=commentList
    *设置默认回答
    */
    public function dodefaultAns(){
        $new_id=common::request('new');
        $comm_id=common::request('comm');
        $this->redis->hset(REDIS_PREFIX.'defaultAns',$new_id,$comm_id);
        echo 1;
    }
    /**
    *+2.5.0
    *@from /c=admin&a=commentList
    *取消默认回答
    */
    public function dodeldefaultAns(){
        $new_id=common::request('new');       
        $this->redis->hdel(REDIS_PREFIX.'defaultAns',$new_id);
        echo 1;
    }
    /**
    *+2.5.0
    *@from /?c=admin&a=hotAns
    *每日热答加热门，精华，置顶，减热门，精华，置顶
    */
    public function doHotBestTop(){
        require_once FILE.'../web/static/kindeditor/php/JSON.php';
        $json = new Services_JSON();

        $action = common::request('action', 'G');   // 操作类型 HomeHot/Best/cancelBest
        $postId = common::request('postId', 'G');   // 帖子id
        $postId = substr($postId, 0,-1);
        $message = '';
        $rel = array();
        $rediskey=REDIS_PREFIX.'hotAns_';
        //echo $rediskey;
        if($action == '' || $postId == '') {
            $message = '参数不完整';
        }
        else {
            $postId = explode(',', $postId);
            foreach ($postId as $id) {
               $tagId=$this->db->getOne("select tagId from r_tagPost where news_id={$id}");
               $tagId=$tagId?:'notag';
               // var_dump($postInfo); 
                $tmp = array('pid' => $id);
                switch ($action) {
                    case 'HomeHot':
                        $this->redis->zincrby($rediskey.'Hot', 20, $id) ;   
                        $this->redis->zincrby($rediskey.'Hot_'.$tagId, 20, $id) ;    
                       // echo $rediskey;
                        $tmp['suc'] =  '成功';               
                        break;
                    case 'cancelHomeHot':
                        $this->redis->zincrby($rediskey.'Hot', -20, $id) ;
                        $this->redis->zincrby($rediskey.'Hot_'.$tagId, -20, $id);
                        $tmp['suc'] =  '成功';  
                        break;
                    case 'Best':
                       $this->redis->zincrby($rediskey.'Best', 20, $id) ;
                       $this->redis->zincrby($rediskey.'Best_'.$tagId, 20, $id) ;
                        $tmp['suc'] = '成功';                       
                        break;
                    case 'cancelBest':
                        $this->redis->zincrby($rediskey.'Best', -20, $id) ;
                        $this->redis->zincrby($rediskey.'Best_'.$tagId, -20, $id) ;
                        $tmp['suc'] = '成功';
                        break;
                    case 'Top':
                        $postInfo = $this->load('bbs')->getPostInfo($id);    
                        if($postInfo['is_show'] == 1)
                        {                            
                            $this->redis->ZADD($rediskey.'Top',time()+30*24*60*60, $id);
                           // echo $rediskey.'Top_'.$tagId;
                            $this->redis->ZADD($rediskey.'Top_'.$tagId,time()+30*24*60*60, $id);
                            $tmp['suc'] = '成功';
                        }
                        else{
                            $tmp['suc'] = '你选择元素没有显示，无法置顶';
                        }
                        break;
                    case 'cancelTop':
                        $this->redis->zrem($rediskey.'Top',$id);
                        $this->redis->zrem($rediskey.'Top_'.$tagId,$id);
                        $tmp['suc'] = '成功';
                        break;
                    default:
                        $tmp['suc'] = '无效操作'; // 参数无效
                        break;
                }
                $rel[] = $tmp;
                unset($tmp,$postInfo);
            }
        }
        echo $json->encode(array('message' => $message, 'rel' => $rel));
        exit;
    }
     /**
     *++v2.5.0
    *装备，想要    
    */
    public function dolikes(){
        $gearId=common::request('gid', 'P');       
        $uid = common::request('uid', 'P');        
        if($this->redis->sadd($this->redisKeyBase.'likes_'.$gearId,$uid)){  
            $this->db->query("update r_gear set likes=likes+1 where gearId={$gearId}");          
        } 
        //如果有老数据，这里可能会返回的数字不一样 ,如果没有老数据最好用redis那行 
        echo  $this->db->getOne("select likes from r_gear where gearId={$gearId}");
        //echo $this->redis->scard($this->redisKeyBase.'likes_'.$gearId);     
    }
     /**
     *++v2.5.0
    *装备，拥有    
    */
    public function dopreossess(){
        $gearId=(int)common::request('gid', 'P');        
        $uid = (int)common::request('uid','P');        
        if($this->redis->sadd($this->redisKeyBase.'preossess_'.$gearId,$uid)){  
            $sql="update r_gear set possess=possess+1 where gearId={$gearId}";
            echo $sql;            
            $this->db->query($sql);          
        }  
        //如果有老数据，这里可能会返回的数字不一样 ,如果没有老数据最好用下边redis那行 
        echo $this->db->getOne("select possess from r_gear where gearId={$gearId}");
        //echo $this->redis->scard($this->redisKeyBase.'preossess_'.$gearId);     
    }
     /**
    *++v2.5.0
    *评论有用    
    */
    public function dousefull(){
        $cid=common::request('cid','P');       
        $uid = (int)common::request('uid','P');      
        if($this->redis->sadd($this->redisKeyBase.'usefull_'.$cid,$uid)){  
            $sql="update r_gear_comment set usefull=usefull+1 where commentId={$cid}";
            //echo $sql;
            $this->db->query($sql);          
        }    
          echo $this->redis->scard($this->redisKeyBase.'usefull_'.$cid);     
    }
    /**
    *++v2.5.0
    *评论没用    
    */
    public function donouse(){
        $cid=common::request('cid','P');       
        $uid = common::request('uid','P');        
        if($this->redis->sadd($this->redisKeyBase.'nouse_'.$cid,$uid)){  
            $sql="update r_gear_comment set  nouse=nouse+1 where commentId={$cid}";
            //echo $sql;
            $this->db->query($sql);          
        }    
          echo $this->redis->scard($this->redisKeyBase.'nouse_'.$cid);     
    }
    /**
    *++v2.5.0
    *@from /?c=admin&a=postInfo
    *跑步装备添加评测时装备id是否存在，返回装备名和装备第一张缩略图
    */
    public function dohasThisGear(){
        $gearId=common::request('id');
        $sql="select name,images,isShow from r_gear where gearId={$gearId}";
        $thisgear=$this->db->getRow($sql);       
        if(!$thisgear)exit(json_encode(['code'=>2,'msg'=>'装备不存在']));
        if(!$thisgear['isShow'])exit(json_encode(['code'=>1,'msg'=>'装备已下架，如要选择请上架装备']));
        $thisgear['images']=json_decode($thisgear['images'],true);
        echo json_encode(['code'=>0,'data'=>$thisgear]);
    }

    /**
    * 装备评论 
    */

    public function domoreComments(){
        $gid=common::request('gearId','G');
        $p=common::request('p','G',1);
        $offset=10;
        $limit=" limit ".($p-1)*$offset.",".$offset;
        $sql="SELECT commentId,r_gear_comment.uid,nickname,header,content,image,thumbImg,score,r_gear_comment.addTime,usefull,nouse FROM r_gear_comment LEFT JOIN r_user ON r_gear_comment.uid=r_user.uid where isShow=1 AND gearId={$gid} order by r_gear_comment.addTime desc {$limit}";

        $list=$this->db->getAll($sql);
        foreach ($list as &$v){
            //格式化时间差
           $v['dateformat']=date("Y-m-d", $v['addTime']);
           $v['image'] = json_decode($v['image'], TRUE);
           $v['thumbImg'] = json_decode($v['thumbImg'], TRUE);
        }

        echo json_encode($list);
    }
    
    /*
     * 搜索装备渠道
     */
    public function doAdminSearchGearChannel(){
        $keywords = trim(common::request('keywords','G'));
        $gearId = common::request('gearId','G',0);
        if(empty($keywords) && empty($gearId)){
            echo json_encode(['code'=>-1]);
        }
        $where = "a.gearId=$gearId";
        if(!empty($keywords)){
           $where = "(" . $where .  " or a.name like '%$keywords%')";
        }
        $sql = "select a.gearId,b.name as title,b.price,b.pic,b.supplier_id,'gear' as type from r_gear a inner join r_gear_channel b on a.goods_id = b.goods_id 
                where ". $where. " and ( b.status=1 and b.item_id is not null) order by b.price asc limit 1000";

        $data = $this->db->getAll($sql);
        $groupons = $this->load('gear')->getGrouponByGearId($gearId);
        foreach ($groupons as $groupon){
            array_unshift($data,array(
                'gearId'=>$gearId,
                'title'=>$groupon['title'],
                'price'=>$groupon['low_price'],
                'pic'=>$groupon['image'],
                'supplier_id'=>$groupon['id'],
                'type'=>'groupon',
            ));
        }

        echo json_encode(['code'=>0,'data'=>$data]);
    }

    /*
    * 装备列表&搜索
    */
    public function doAdminSearchGear(){
        $keywords = trim(common::request('keywords','G'));
        $sql = "select gearId as id,name  from r_gear where isShow=1 and name like '%$keywords%' order by addTime desc limit 10";
        $data = $this->db->getAll($sql);
        echo  json_encode($data);
    }



    /*
     * 装备推荐
     */
    public function dorecommendGear(){
        $page = (int)common::request('page','G',1);
        $list = $this->load('gear')->getHomeRecommendGear($page);
        foreach ($list as & $v) {
            $v['images'] = !empty($v['images'])?$v['images'][0]:'';
        }
        $result = array();
        $result['list'] = array_slice($list, 0,20);
        echo json_encode($result);
    }

    /*
     * 装备帖子
     */
    public function doGearNewsList(){
        $page = (int)common::request('page','G',1);
        $sort = (int)common::request('sort','G',1);
        $num  = 10;

        $newsList = $this->load('gear')->getHomeNewsList($page,$sort,$num+1);

        $result = array();
        $result['list'] = array_slice($newsList, 0,$num);
        $result['isNext'] = count($newsList)>$num;
        echo json_encode($result);
    }

    /*
     * 装备列表&搜索
     */
    public function doGearList(){
        $catId = (int)common::request('catId','G','');
        $page = (int)common::request('page','G',1);
        $brand = (int)common::request('brand','G','');
        $sex = (int)common::request('sex','G','');
        $price = common::request('price','G','');
        $w = common::request('w','G','');
        $order = (int)common::request('order','G','');

        if($catId==3){
            $sex='';
        }

        $ids = $this->load('gear')->getGearList($w,$catId, $sex, $price, $brand,$order ,$page,21);

        $list = array();
        if(!empty($ids)){
            foreach ($ids as & $v) {
                $gear = $this->load('gear')->getGearInfo($v['gearId']);
                $gear['images'] = !empty($gear['images'])?$gear['images'][0]:'';
                $gear['shortDesc'] = strip_tags($gear['shortDesc']);
                $list[] = $gear;
            }
        }
        $result = array();
        $result['list'] = array_slice($list, 0,20);
        $result['isNext'] = count($list)>20;
        echo json_encode($result);
    }

     /*
     * 团购
     */
    public function doGrouponList(){
        $page = (int)common::request('page','G',1);
        $sort = (int)common::request('sort','G',1);
        $num  = 20;

        $newsList = $this->load('gear')->getGrouponList($page,$sort,$num+1);

        $result = array();
        $result['list'] = array_slice($newsList, 0,$num);
        $result['isNext'] = count($newsList)>$num;

        echo json_encode($result);
    }

    /*
     * 搜索淘宝商品信息
     */
    public function doAdminSearchTao(){
        $url = common::request('url','');
        preg_match_all('/id=(\\d+)/', $url, $m);
        $item_id = $m[1][0];

        $sql = "select id,name,price,pic from r_gear_channel where item_id=$item_id order by id desc";
        $result = $this->db->getRow($sql);
        if(empty($result)) {
            $url = urlencode($url);
            $taobao = common::getContents("http://taoapi.ijoggers.com/?code=linjiangjian&url=$url",
                null,15);
            $taobao = json_decode($taobao);
            if (empty($taobao)) {
                echo json_encode(array('error' => true));
                exit;
            } elseif(!empty($taobao->title)) {
                $params = array(
                    'name' => $taobao->title,
                    'pic' => $taobao->img,
                    'price' => $taobao->price,
                    'item_id' => $item_id,
                    'status'=>1
                );
                $this->db->insertRowTable('r_gear_channel', $params);
                $sql = "select id,name,price,pic from r_gear_channel where item_id=$item_id order by id desc";
                $result = $this->db->getRow($sql);
            }
        }
        echo json_encode($result);
    }

    public function doAdminUploadChannelPic(){
        $id = common::request('picChannelId','');
        $price = common::request('picChannelPrice','');
        if (!$_FILES || ($_FILES['picFile']['size'] == 0)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'请选择上传文件!'));
            exit;
        }

        $imageName ='tao_'.md5(microtime(TRUE).$_FILES['picFile']['name']);
        $image_url = $this->load('qiniu')->uploadQiNiuImg('picFile',$imageName);
        $this->db->updateRowTable('r_gear_channel',array(
            'id'=>$id,
            'pic'=>$image_url,
            'price'=>$price
        ));
        echo json_encode(array('status'=>'ok','error_msg'=>'上传成功','image'=>$image_url));
    }


}